<!-- 投塘信息管理 -->
<template>
  <MainSlot v-loading="loading">
    <template v-slot:title>
      <span>投塘信息管理</span>
    </template>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:table v-loading="loading">
      <div v-if="resetPindInfo" class="pontInfoContent">
        <PontInfo :ref="`pontInfoRef_${index}`" :pontInfoIndex="index" v-for="item, index in pontInfoList"
          :pontInfo="item" :key="index" @handleEvent="addData(item)" @viewDetails="viewDetails"></PontInfo>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page"
        :total="total">
      </Pagination>
    </template>s
    <template v-slot:dialogModule>
      <div class="guideBox" v-if="isGuide">
        <div class="routerInfo" :style="guideStyle" v-if="isGuide && guideInfo.index > 0 && guideInfo.procedure.length">
          <div class="guideText">{{ guideIndex + 1 }}. {{ guideInfo.procedure && guideInfo.procedure.length >
            0 ?
            guideInfo.procedure[guideIndex]
            : '' }}</div>
          <div class="guideNext" @click="guideNext" v-if="guideInfo.procedure.length > (guideIndex + 1)">下一步
          </div>
        </div>
      </div>
      <AddEdit :title="'投塘信息'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :facilityList="facilityList"
        :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
      <DetailData @closeDialog="closeDialog" @queryFishPond="queryFishPond" :dialogVisible="detailDataVisible"
        :data="viewDetailsData"></DetailData>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import PontInfo from './components/pontInfo.vue';
import AddEdit from './components/addEdit.vue';
import DetailData from './components/detailData.vue';
import pondInformationManagement from '@/api/pondManagment/pondInformationManagement.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import varietyManagement from '@/api/basicInformation/varietyManagement.js';
import specificationManagement from '@/api/basicInformation/specificationManagement.js';
import staffManage from '@/api/basicInformationOperate/staffManage';
import batch from '@/api/batch/batchManagement';
// detailData

export default {
  components: { MainSlot, Pagination, SearchForm, PontInfo, AddEdit, DetailData },
  data() {
    return {
      guideIndex: 0,
      guideStyle: {},
      unfoldFlag: false,
      resetPindInfo: false,
      loading: false,
      dialogVisible: false,
      detailDataVisible: false,
      addEditFlag: 'add',
      selectList: [],
      searchFormData: {},
      pontInfoList: [],
      viewDetailsData: {},
      formData: {},
      page: 1,
      size: 2,
      total: 10,
      selectIndex: 0,
      dataList: [],
      varietyList: [],
      facilityList: [],
      specificationList: [],
      batchList: [],
      personList: [],
      facilityObj: {},
      formItemList: [
        {
          label: '选择批次',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '选择品种',
          type: 'select',
          selectOptions: [],
          param: 'plantVarietyId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '设施名称',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '封塘状态',
          type: 'select',
          selectOptions: [{
            text: '封塘', value: true
          }, {
            text: '未封塘', value: false
          }],
          param: 'status',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
      ]
    }
  },
  computed: {
    guideInfo() {
      return this.$store.state.user.guideInfo;
    },
    isGuide() {
      return this.$store.state.user.isGuide || ''
    },
  },
  watch: {
    guideInfo: {
      handler(v) {
        this.setGuide(v)
      },
      deep: true
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    guideNext() {
      let { index, procedure } = this.guideInfo;
      this.$store.dispatch("user/getGuideInfo", {
        procedure: procedure,
        index: index + 1
      });
    },
    setGuide(v) {
      if (!this.isGuide) return;
      let { index } = v;
      this.guideIndex = index;
      let btn = document.getElementById('guide_add_0');
      // this.resetGuide(btn);
      if (btn) {
        if (index == 1) {
          btn.className += " guide-name";
          console.log('选中了', btn, btn.className)
          this.guideStyle = {
            top: '20%',
            right: '30%',
            wayFlag: 'right'
          }
        } else if (index == 2) {
          if (this.pontInfoList.length) this.addData(this.pontInfoList[0]);
        }
      }
    },
    resetGuide(node) {
      if (node) {
        node && (node.className = node.className.replace("guide-name", ""))
      }
    },
    search(data) {
      this.page = 1;
      this.searchFormData = { ...this.searchFormData, ...data };
      this.queryFishPond();
    },
    //先分页查询鱼塘，通过鱼塘id集合查询鱼塘投塘列表
    async queryFishPond() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          breedType: sessionStorage.breedType,
          ...this.searchFormData,
        }
      };
      this.loading = true;
      this.resetPindInfo = false;
      let { data: fishPond } = await facilityManagement.queryBatchPageByCondition(params);
      this.loading = false;
      let fishPondList = fishPond.content || [];
      fishPondList = fishPondList.map(item => {
        return {
          ...item,
          facilityName: this.facilityObj[item.facilityId]
        }
      })
      this.total = fishPond.totalElements;
      if (fishPond.totalPages && this.page > fishPond.totalPages) {
        this.page = fishPond.totalPages;
        this.queryFishPond();
      };

      let fishPondIdList = [];
      fishPondList.forEach(item => {
        fishPondIdList.push(item.facilityId);
      });
      let { data: list } = await pondInformationManagement.queryDetailByFacilityIdList(fishPondIdList);
      this.pontInfoList = [];
      //合并鱼塘和查询过来的鱼塘投塘数据
      fishPondList.forEach((item, index) => {
        this.$set(this.pontInfoList, index, { ...item, inputInfo: list.find(pond => { return item.facilityId == pond.facilityId }) || {} })
      });
      setTimeout(() => {
        this.setGuide(this.guideInfo);
      }, 500);
      this.resetPindInfo = true;
    },
    async initData() {
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' });
      let { data: specificationList } = await specificationManagement.queryByCondition({})
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({ breedType: sessionStorage.breedType });
      let { data: personList } = await staffManage.queryByCondition({ status: true })

      this.queryFishPond();
      this.batchList = batchList || [];
      this.specificationList = specificationList || [];
      this.varietyList = varietyList || [];
      this.facilityList = facilityList || [];
      this.facilityObj = {};
      this.facilityList.forEach(item => {
        this.facilityObj[item.facilityId] = item.facilityName
      })
      this.personList = personList.map(item => {
        return {
          staffId: item.person.personId,
          staffName: item.person.name,
          ...item
        }
      });
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'plantVarietyId') {
          let selectOptions = this.varietyList.map(data => {
            console.log(data.plantVarietyName)
            return {
              text: data.plantVarietyName, value: data.plantVarietyId
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    //查看详情
    viewDetails(data) {
      console.log(data)
      this.viewDetailsData = JSON.parse(JSON.stringify(data))
      this.detailDataVisible = true;
    },
    //添加投塘
    addData(item) {
      this.dialogVisible = true;
      this.formData = JSON.parse(JSON.stringify(item))
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryFishPond();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 操作方法
    handleRow(rowData, item) {
      console.log(rowData, item);
      if (item.flag == 'add') {
        this.dialogVisible = true;
      } else if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'delete') {
        this.delData();
      }
      this.addEditFlag = item.flag
    },
    /**
     * 
     * @param {Array} delDataList  //删除的集合
     * @param {String} label  //几个元素对应的id键值
     */
    delData(delDataList, label) {
      console.log(delDataList)
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.detailDataVisible = false;
      this.queryFishPond();
    },
  }
};
</script>
<style lang="scss" scoped>
.pontInfoContent {
  height: 100%;
  overflow: auto;
}

.guideBox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #00000030;
  z-index: 10;
}


.routerInfo {
  max-width: 400px;
  min-width: 300px;
  padding: 10px;
  background-color: #FF9243;
  color: #ffffff;
  position: fixed;
  z-index: 9999;

  .guideText {
    width: 100%;
    text-align: left;
    line-height: 26px;
  }

  .guideNext {
    width: 100px;
    margin-top: 15px;
    background-color: #e4a579;
    border: 1px solid #c65504;
    border-radius: 4px;
    text-align: center;
    line-height: 28px;
    cursor: pointer;

    &:hover {
      background-color: #d88244;
    }
  }
}

::v-deep {

  .el-table--border::after,
  .el-table--group::after,
  .el-table::before {
    z-index: 0;
  }

  .el-checkbox__inner {
    z-index: 0;
  }
}
</style>